﻿Imports System.Runtime.InteropServices
Imports System.Globalization

Public Class BSFKAttend
    Dim dtEnroll As New DataTable
    Dim serverName1 As String
    Dim lisence As Integer = 1261

    Public Sub New(ByVal serverName As String)
        'Lay gia tri serverName ben Form
        serverName1 = serverName
    End Sub

#Region "Check Connect"
    '/******************************************************************/
    '/*                      Check Connect NetworkMode                 */
    '/******************************************************************/
    Public Function CheckConnectNet(ByVal machineNo As Integer,
                                        ByVal ipAddress As String,
                                        ByVal port As Integer,
                                        ByVal timeOut As Integer,
                                    ByVal chkUDP As Boolean,
                                    ByVal password As Integer,
                                    ByVal lisence As Integer) As Integer
        If chkUDP = False Then
            Return FK_ConnectNet(machineNo, ipAddress, port, timeOut, PROTOCOL_TCPIP, password, lisence)
        Else
            Return FK_ConnectNet(machineNo, ipAddress, port, timeOut, PROTOCOL_UDP, password, lisence)
        End If
    End Function

    '/******************************************************************/
    '/*                      Check Connect USB Mode                    */
    '/******************************************************************/
    Public Function CheckConnectUSB(ByVal machineNo As Integer, ByVal lisence As Integer) As Integer
        Return FK_ConnectUSB(machineNo, lisence)
    End Function

    '/******************************************************************/
    '/*                      Check Connect Serial Mode                 */
    '/******************************************************************/
    Public Function CheckConnectSerial(ByVal machineNo As Integer, ByVal comPort As Integer,
                                       ByVal baudRate As Integer, ByVal chkModem As Boolean,
                                       ByRef telNumber As String, ByRef timeDial As Integer,
                                       ByVal linsence As Integer) As Integer
        If chkModem Then
            If timeDial < 10 And timeDial > 60 Then
                timeDial = 10
            Else
                telNumber = ""
                timeDial = 0
            End If
        End If
        Return FK_ConnectComm(machineNo, comPort, baudRate, telNumber, timeDial, linsence)
    End Function
#End Region

#Region "Disconnect"
    '/******************************************************************/
    '/*                      Check Connect NetworkMode                 */
    '/******************************************************************/
    Public Sub Disconnect(ByVal fnCommHandleIndex As Long)
        FK_DisConnect(fnCommHandleIndex)
    End Sub
#End Region

#Region "Get All Enroll Data"
    '/******************************************************************/
    '/*                Function Get All Enroll Data                    */
    '/******************************************************************/

    Public Function GetAllEnroll(ByVal fnCommHandleIndex As Long) As DataTable
        dtEnroll = dtEnrollFormat()
        Dim vEnrollNumber As Integer
        Dim vEnrollName As String
        Dim vBackupNumber As Integer
        Dim vPrivilege As Integer
        Dim vnEnableFlag As Integer
        Dim vnMessRet As Integer
        Dim vTitle As String
        Dim vnResultCode As Integer
        Dim vEnrollData As String = Space(7354)
        Dim vNumber As Integer = 1

        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return Nothing
        End If

        vnResultCode = FK_ReadAllUserID(fnCommHandleIndex)
        If vnResultCode <> RUN_SUCCESS Then
            Return Nothing
        End If
        While (FK_GetAllUserID(fnCommHandleIndex, vEnrollNumber, vBackupNumber, vPrivilege, vnEnableFlag) = 1)
            vnResultCode = FK_GetEnrollDataWithString(fnCommHandleIndex, vEnrollNumber, vBackupNumber, vPrivilege, vEnrollData)
            dtEnroll.Rows.Add({vNumber, fnCommHandleIndex, vEnrollNumber, vBackupNumber, vPrivilege, vnEnableFlag, vEnrollData})
            vNumber += 1
        End While
        Return dtEnroll
    End Function
#End Region

#Region "Get All Log Data"
    Public Function GetAllLogData(ByVal fnCommHandleIndex As Long) As DataTable

        Dim dtAllLog As New DataTable
        dtAllLog.Columns.Add("EnrollNumber")
        dtAllLog.Columns.Add("VerifyMode")
        dtAllLog.Columns.Add("InOutMode")
        dtAllLog.Columns.Add("Date")
        dtAllLog.Columns.Add("Time")
        Dim vEnrollNumber As Long
        Dim verifyMode As Integer
        Dim inoutMode As Integer
        Dim dateTime As Date
        Dim vnResultCode As Integer

        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return Nothing
        End If
        vnResultCode = FK_LoadGeneralLogData(fnCommHandleIndex, 1)
        While FK_GetGeneralLogData(fnCommHandleIndex, vEnrollNumber, verifyMode, inoutMode, dateTime) = 1
            dtAllLog.Rows.Add(vEnrollNumber, verifyMode, inoutMode, dateTime.Year * 10000 + dateTime.Month * 100 + dateTime.Day, dateTime.Hour * 100 + dateTime.Minute)
        End While

        Return dtAllLog

    End Function
#End Region

#Region "Empty Enroll data"
    '/******************************************************************/
    '/*                        Function empty Enroll                   */
    '/******************************************************************/

    Public Function EmptyEnrollData(ByVal fnCommHandleIndex As Long) As Boolean
        Dim vnResultCode As Integer
        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return False
        End If

        vnResultCode = FK_EmptyEnrollData(fnCommHandleIndex)

        FK_EnableDevice(fnCommHandleIndex, 1)
        Return True
    End Function
#End Region

#Region "Manager User"
    '/******************************************************************/
    '/*                Function Enable/Disable User                    */
    '/******************************************************************/

    Public Function SetUser(ByVal fnCommHandleIndex As Long, ByVal enableUser As Boolean, ByVal enrollNumber As Integer, ByVal backupNumber As Integer) As Boolean
        Dim vEnrollNumber As Integer = enrollNumber
        Dim vBackupNumber As Integer = backupNumber
        Dim vnResultCode As Integer
        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return False
        End If

        vnResultCode = FK_EnableUser(fnCommHandleIndex, vEnrollNumber, vBackupNumber, enableUser)
        FK_EnableDevice(fnCommHandleIndex, 1)
        Return True
    End Function

    '/******************************************************************/
    '/*                Function modify Privilege                       */
    '/******************************************************************/

    Public Function ModifyPrivilege(ByVal fnCommHandleIndex As Long, ByVal enrollNumber As Integer, ByVal backupNumber As Integer,
                                    ByVal privilege As Integer) As Boolean
        Dim vEnrollNumber As Integer = enrollNumber
        Dim vBackupNumber As Integer = backupNumber
        Dim vPrivilege As Integer = privilege
        Dim vnResultCode As Integer
        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return False
        End If

        vnResultCode = FK_ModifyPrivilege(fnCommHandleIndex, vEnrollNumber, vBackupNumber, vPrivilege)
        FK_EnableDevice(fnCommHandleIndex, 1)

        Return True
    End Function

    '/******************************************************************/
    '/*                        Function Delete User                    */
    '/******************************************************************/

    Public Function DeleteEnrollData(ByVal fnCommHandleIndex As Long, ByVal enrollNumber As Integer, ByVal backupNumber As Integer) As Boolean
        Dim vEnrollNumber As Integer = enrollNumber
        Dim vBackupNumber As Integer = backupNumber
        Dim vnResultCode As Integer
        vnResultCode = FK_EnableDevice(fnCommHandleIndex, 0)
        If vnResultCode <> RUN_SUCCESS Then
            Return False
        End If

        vnResultCode = FK_DeleteEnrollData(fnCommHandleIndex, vEnrollNumber, vBackupNumber)
        If vnResultCode = RUN_SUCCESS Then
            Return True
        Else
            Return False
        End If
        FK_EnableDevice(fnCommHandleIndex, 1)

    End Function
#End Region

#Region "Set Alarm"

    '/******************************************************************/
    '/*                      Set Alarm to FP Terminal                  */
    '/******************************************************************/
    Public Sub SetAlarm(ByVal machineNo As Integer,
                                        ByVal ipAddress As String,
                                        ByVal port As Integer,
                                        ByVal timeOut As Integer,
                                    ByVal chkUDP As Boolean,
                                    ByVal password As Integer,
                                    ByVal lisence As Integer, ByVal deviceNo As Integer,
                                    ByVal bellCount As Integer,
                                    ByVal bellValue As String)
        Dim fnCommHandleIndex As Long
        Dim vnResultCode As Integer
        'Connect to FP terminal
        If deviceNo = DEVICENAME_USB Then
            fnCommHandleIndex = CheckConnectUSB(machineNo, lisence)
        Else
            fnCommHandleIndex = CheckConnectNet(machineNo, ipAddress, port, timeOut, chkUDP, password, lisence)
        End If

        'Set Alarm
        vnResultCode = FK_SetBellTimeWithString(fnCommHandleIndex, bellCount, bellValue)

        'Disconnect
        FK_DisConnect(fnCommHandleIndex)

    End Sub


#End Region

#Region "Get All User Data From FP Terminal register"

    '/******************************************************************/
    '/*             Get All User Data From FP Terminal                 */
    '/******************************************************************/
    'return datatable use data of FPTerminal register

    Public Function GetAllUserDataRegister() As DataTable

        'Get data of FP register
        Dim bsTerminalSetting As New BSTerminalSetting(serverName1)
        Dim dt As DataTable = Nothing
        Dim arrayDataOfTerminal() As Object = bsTerminalSetting.CheckLeastFPTerminalRegister()
        Dim fnCommHandleIndex As Long
        Dim vnResultCode As Integer
        If Not arrayDataOfTerminal(0).Equals(vbNull) Then
            'Connect to this FP Terminal
            If CInt(arrayDataOfTerminal(1)) = DEVICE_USB Then
                fnCommHandleIndex = FK_ConnectUSB(CInt(arrayDataOfTerminal(0)), lisence)
            Else
                fnCommHandleIndex = FK_ConnectNet(CInt(arrayDataOfTerminal(0)), arrayDataOfTerminal(2).ToString(), CInt(arrayDataOfTerminal(3)), 5000, PROTOCOL_TCPIP, 0, lisence)
            End If

            If fnCommHandleIndex > 0 Then
                'MsgBox(GetAllEnroll(fnCommHandleIndex).Rows.Count)
                Return GetAllEnroll(fnCommHandleIndex)
            Else
                Return Nothing
            End If
        End If
        Return Nothing
    End Function

#End Region

    '//================== Save user data when load from FP register ===============//
#Region "Save All User Data From FP Terminal register"
    '/******************************************************************/
    '/*                Save User data of FP terminal register          */
    '/******************************************************************/
    Public Function SaveUserData() As Integer
        Dim bsTerminalUserData As New BSTerminalUserData(serverName1)
        Dim dtAllUserDataRegister As DataTable = GetAllUserDataRegister()
        If IsNothing(dtAllUserDataRegister) Then
            Exit Function
        End If
        Dim dtAllTerminalUserData As DataTable = bsTerminalUserData.GetAllTerminalUserData()
        'Check if user data in DB = null --> save all data
        '       else check ID --> save
        If dtAllTerminalUserData.Rows.Count = 0 Then
            If Not IsNothing(dtAllUserDataRegister) Then
                For i As Integer = 0 To dtAllUserDataRegister.Rows.Count - 1
                    bsTerminalUserData.InsertTerminalUserData(CInt(dtAllUserDataRegister.Rows.Item(i).Item(2)), CInt(dtAllUserDataRegister.Rows.Item(i).Item(3)),
                                                             CInt(dtAllUserDataRegister.Rows.Item(i).Item(4)), dtAllUserDataRegister.Rows.Item(i).Item(6).ToString(), CInt(dtAllUserDataRegister.Rows.Item(i).Item(5)), Date.Now, Date.Now)
                Next
            End If
        Else
            '//================== Save DB with 2 for loop ===============//
            'Dim flag As Boolean
            'For i As Integer = 0 To dtAllUserDataRegister.Rows.Count - 1
            '    flag = False
            '    For j As Integer = 0 To dtAllTerminalUserData.Rows.Count - 1
            '        If CInt(dtAllUserDataRegister.Rows.Item(i).Item(2)) <> dtAllTerminalUserData.Rows.Item(j).Item(0) Then
            '            flag = True
            '        Else
            '            flag = False
            '            Exit For
            '        End If
            '    Next
            '    If flag = True Then
            '        bsTerminalUserData.InsertTerminalUserData(CInt(dtAllUserDataRegister.Rows.Item(i).Item(2)), CInt(dtAllUserDataRegister.Rows.Item(i).Item(3)),
            '                                            CInt(dtAllUserDataRegister.Rows.Item(i).Item(4)), dtAllUserDataRegister.Rows.Item(i).Item(6).ToString(), 1, Date.Now, Date.Now)
            '    End If
            'Next

            For i As Integer = 0 To dtAllUserDataRegister.Rows.Count - 1

                Try
                    bsTerminalUserData.InsertTerminalUserData(CInt(dtAllUserDataRegister.Rows.Item(i).Item(2)), CInt(dtAllUserDataRegister.Rows.Item(i).Item(3)),
                                                        CInt(dtAllUserDataRegister.Rows.Item(i).Item(4)), dtAllUserDataRegister.Rows.Item(i).Item(6).ToString(), CInt(dtAllUserDataRegister.Rows.Item(i).Item(5)), Date.Now, Date.Now)
                Catch ex As Exception
                    bsTerminalUserData.UpdateTerminalUserData(CInt(dtAllUserDataRegister.Rows.Item(i).Item(2)), CInt(dtAllUserDataRegister.Rows.Item(i).Item(3)),
                                                        CInt(dtAllUserDataRegister.Rows.Item(i).Item(4)), dtAllUserDataRegister.Rows.Item(i).Item(6).ToString(), CInt(dtAllUserDataRegister.Rows.Item(i).Item(5)), Date.Now)
                End Try
            Next

        End If
        'Disconnect FP Terminal

    End Function


#End Region

    '//================== Get all log data of FP attend -> return arraylist datatable===============//
#Region "Get all log data of FP Terminal attendance"
    Public Function GetAllLogDataAttend() As ArrayList

        Dim arrayDTLog As New ArrayList
        Dim fnCommHandleIndex As Long
        Dim vnResultCode As Integer
        'Get data of FP Terminal Attendance
        Dim bsTerminalSetting As New BSTerminalSetting(serverName1)
        Dim dtFKAttend As DataTable = bsTerminalSetting.GetFPTerminal()

        If dtFKAttend.Rows.Count <> 0 Then
            For i As Integer = 0 To dtFKAttend.Rows.Count - 1
                If CInt(dtFKAttend.Rows.Item(i).Item(1)) = DEVICE_USB Then
                    fnCommHandleIndex = FK_ConnectUSB(CInt(dtFKAttend.Rows.Item(i).Item(0)), lisence)
                    If fnCommHandleIndex > 0 Then
                        arrayDTLog.Add(GetAllLogData(fnCommHandleIndex))
                        Disconnect(fnCommHandleIndex)
                    End If
                Else
                    fnCommHandleIndex = FK_ConnectNet(CInt(dtFKAttend.Rows.Item(i).Item(0)), dtFKAttend.Rows.Item(i).Item(2).ToString(), CInt(dtFKAttend.Rows.Item(i).Item(3)), 5000, PROTOCOL_TCPIP, 0, lisence)
                    If fnCommHandleIndex > 0 Then
                        arrayDTLog.Add(GetAllLogData(fnCommHandleIndex))
                        Disconnect(fnCommHandleIndex)
                    End If
                End If
            Next
        End If
        'MsgBox(arrayDTLog.Count)
        Return arrayDTLog

    End Function
#End Region

    '//================== Insert default log data of FP attend ===============//

    '//================== Save all log data of FP attend ===============//
#Region "Save all log data from list FP attend"

    Public Function SaveLogData() As Integer
        Try
        'Lay tat ca Log cua cac may dung de cham cong (array list cac table)
        Dim alLogData As ArrayList = GetAllLogDataAttend()

        'Lay du lieu tat ca cac may dung de cham cong
        Dim bsTerminalSetting As New BSTerminalSetting(serverName1)
        Dim dtFKAttend As DataTable = bsTerminalSetting.GetFPTerminal()

        'Kiem tra phai phai co may dung de cham cong
        If dtFKAttend.Rows.Count <> 0 Then
            'Duyet cac may cham cong
            For i As Integer = 0 To dtFKAttend.Rows.Count - 1

                'Lay use type cua may
                Dim useType As Integer = dtFKAttend.Rows.Item(i).Item(4)
                'Lay du lieu Log cua may
                Dim dt As DataTable = alLogData(i)
                'MsgBox(dt.Rows.Count)

                Dim max As String

                'Kiem tra neu may la chi dung de Di Lam
                If useType = USETYPE_ONLYONDUTY Then
                    'Lay gia tri gio di lam phu hop va luu vao DB
                    For j As Integer = 0 To dt.Rows.Count - 1
                            If dt.Rows.Item(j).Item(2) = LOG_IOMODE_IN Then
                                'Update record vao csdl (SEND enrollNo, date, time)
                                'Duyet tung record va update vao csdl

                                'Truy van employee_No tu ID duoi may
                                Dim bsEmployee As New BSEmployee(serverName1)

                                'Goi phuong thuc updateTimetoWorkData cua BSWorkData
                                Dim bsWorkData As New BSWorkData(serverName1)
                                MsgBox(j)
                                bsWorkData.UpdateStartTimeToWorkData(bsEmployee.GetEmployeeNoFromEnrollNo(CInt(dt.Rows.Item(j).Item(0))), CInt(dt.Rows.Item(j).Item(3)), CInt(dt.Rows.Item(j).Item(4)), Nothing)
                            End If
                    Next
                End If

                'Kiem tra neu may la chi dung de Ra ve
                If useType = USETYPE_ONLYOFFDUTY Then
                    'Lay gia tri gio ra ve phu hop va luu vao DB
                    For j As Integer = 0 To dt.Rows.Count - 1
                            If dt.Rows.Item(j).Item(2) = LOG_IOMODE_OUT Then
                                'Update record vao csdl (SEND enrollNo, date, time)
                                'Duyet tung record va update vao csdl

                                'Truy van employee_No tu ID duoi may
                                Dim bsEmployee As New BSEmployee(serverName1)

                                'Goi phuong thuc updateTimetoWorkData cua BSWorkData
                                Dim bsWorkData As New BSWorkData(serverName1)
                                bsWorkData.UpdateStartTimeToWorkData(bsEmployee.GetEmployeeNoFromEnrollNo(CInt(dt.Rows.Item(j).Item(0))), CInt(dt.Rows.Item(j).Item(3)), Nothing, CInt(dt.Rows.Item(j).Item(4)))
                            End If
                    Next
                End If

                'Kiem tra neu may la vua di lam va ra ve
                If useType = USETYPE_BOTHONOFFDUTY Or useType = USETYPE_ALL Then
                        'Lay gia tri gio phu hop va luu vao DB
                        For j As Integer = 0 To dt.Rows.Count - 1
                            If dt.Rows.Item(j).Item(2) = LOG_IOMODE_IN Then
                                'Update record vao csdl (SEND enrollNo, date, time)
                                'Duyet tung record va update vao csdl

                                'Truy van employee_No tu ID duoi may
                                Dim bsEmployee As New BSEmployee(serverName1)

                                'Goi phuong thuc updateTimetoWorkData cua BSWorkData
                                Dim bsWorkData As New BSWorkData(serverName1)
                                bsWorkData.UpdateStartTimeToWorkData(bsEmployee.GetEmployeeNoFromEnrollNo(CInt(dt.Rows.Item(j).Item(0))), CInt(dt.Rows.Item(j).Item(3)), CInt(dt.Rows.Item(j).Item(4)), Nothing)
                            End If
                            If dt.Rows.Item(j).Item(2) = LOG_IOMODE_OUT Then
                                'Update record vao csdl (SEND enrollNo, date, time)
                                'Duyet tung record va update vao csdl

                                'Truy van employee_No tu ID duoi may
                                Dim bsEmployee As New BSEmployee(serverName1)

                                'Goi phuong thuc updateTimetoWorkData cua BSWorkData
                                Dim bsWorkData As New BSWorkData(serverName1)
                                bsWorkData.UpdateStartTimeToWorkData(bsEmployee.GetEmployeeNoFromEnrollNo(CInt(dt.Rows.Item(j).Item(0))), CInt(dt.Rows.Item(j).Item(3)), Nothing, CInt(dt.Rows.Item(j).Item(4)))
                            End If
                        Next
                End If

            Next

        End If
        Catch ex As Exception
            System.Console.WriteLine(ex.Message)
        End Try
    End Function

#End Region

    '//================== Return Datatable Enroll Fomat ===============//
    Public Function dtEnrollFormat() As DataTable
        Dim dtEnroll1 As New DataTable
        dtEnroll1.Columns.Add("No.")
        dtEnroll1.Columns.Add("MachineNo")
        dtEnroll1.Columns.Add("EnrollNumber")
        dtEnroll1.Columns.Add("BackupNumber")
        dtEnroll1.Columns.Add("Privilege")
        dtEnroll1.Columns.Add("Status")
        dtEnroll1.Columns.Add("EnrollData")
        Return dtEnroll1
    End Function

    '//================== Return String IPAddress Fomat ===============//
    Public Function FormatIPAddress(ByVal ipAddress As String) As String
        Dim arrayStr() As String = ipAddress.Split(".")
        Dim arrayInt(4) As Integer
        arrayInt(0) = CInt(arrayStr(0))
        arrayInt(1) = CInt(arrayStr(1))
        arrayInt(2) = CInt(arrayStr(2))
        arrayInt(3) = CInt(arrayStr(3))
        Return arrayInt(0) & "." & arrayInt(1) & "." & arrayInt(2) & "." & arrayInt(3)
    End Function

End Class
